package cn.tyoui.BaiduTranslate;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import cn.tyoui.commonenum.Coding;
import cn.tyoui.commonenum.Language;
import cn.tyoui.tools.Tools;

/**
 * 百度翻译类
 * 
 * @author 张伟
 * @version 1.0
 *
 */
public class BaiduTranslateTools implements Tools {

	private static BaiduTranslateTools tools = null;

	public static BaiduTranslateTools initTool() {
		if (tools == null)
			return tools = new BaiduTranslateTools();
		return tools;
	}

	private BaiduTranslateTools() {
	}

	/**
	 * 默认格式是UTF-8
	 */
	private String UTF8 = Coding.UTF8.toString();

	/**
	 * 申请者开发者id，实际使用时请修改成开发者自己的appid
	 */
	private String appId = "2015063000000001";

	/**
	 * 申请成功后的证书token，实际使用时请修改成开发者自己的token
	 * 
	 */
	private String token = "12345678";

	/**
	 * 百度翻译的网址
	 */
	private String url = "http://api.fanyi.baidu.com/api/trans/vip/translate";

	/**
	 * 随机数，用于生成md5值
	 */
	private Random random = new Random();

	/**
	 * 没有翻译之前的英语
	 */
	private String from = "en";

	/**
	 * 翻译成汉语
	 */
	private String to = "zh";

	public String translate(String word) throws Exception {
		return translate(word, from, to);
	}

	/**
	 * 百度翻译
	 * 
	 * @param word
	 *            需要翻译的单词
	 * @param from
	 *            没有翻译是什么语言
	 * @param to
	 *            想翻译成什么语言
	 * @return 翻译的结果
	 * @throws Exception
	 *             网址请求失败
	 */
	public String translate(String word, String from, String to) throws Exception {
		int salt = random.nextInt(10000);
		StringBuilder md5String = new StringBuilder();
		md5String.append(appId).append(word).append(salt).append(token);
		String md5 = DigestUtils.md5Hex(md5String.toString());
		HttpPost httpost = new HttpPost(url);
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		nvps.add(new BasicNameValuePair("q", word));
		nvps.add(new BasicNameValuePair("from", from));
		nvps.add(new BasicNameValuePair("to", to));
		nvps.add(new BasicNameValuePair("appid", appId));
		nvps.add(new BasicNameValuePair("salt", String.valueOf(salt)));
		nvps.add(new BasicNameValuePair("sign", md5));
		httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
		CloseableHttpClient httpclient = HttpClients.createDefault();
		CloseableHttpResponse response = httpclient.execute(httpost);
		HttpEntity entity = response.getEntity();
		InputStream returnStream = entity.getContent();
		BufferedReader reader = new BufferedReader(new InputStreamReader(returnStream, UTF8));
		StringBuilder result = new StringBuilder();
		String str = null;
		while ((str = reader.readLine()) != null)
			result.append(str + "\n");
		if (result.toString() == null)
			return "翻译失败！";
		JSONObject resultJson = new JSONObject(result.toString());
		String e = error(resultJson);
		if (e != null)
			return e;
		JSONArray array = (JSONArray) resultJson.get("trans_result");
		JSONObject dst = (JSONObject) array.get(0);
		String text = dst.getString("dst");
		text = URLDecoder.decode(text, UTF8);
		return text;
	}

	/**
	 * 处理翻译过程中错误信息
	 * 
	 * @param resultJson
	 *            Json信息
	 * @return 错误信息
	 */
	private String error(JSONObject resultJson) {
		try {
			String error = resultJson.getString("error_code");
			switch (error) {
			case "58001":
				return "翻译错误:译文语言方向不支持";
			case "52001":
				return "";
			case "52002":
				return "翻译错误:系统错误";
			case "52003":
				return "翻译错误:未授权用户";
			case "54000":
				return "翻译错误:必填参数为空";
			case "54001":
				return "翻译错误:签名错误";
			case "54003":
				return "翻译错误:访问频率受限";
			case "54004":
				return "翻译错误:账户余额不足";
			case "54005":
				return "翻译错误:长query请求频繁";
			case "58000":
				return "翻译错误:客户端IP非法";
			}
		} catch (Exception e) {
		}
		return null;
	}

	/**
	 * 设置语言
	 * 
	 * @param from
	 *            本身语言
	 * @param to
	 *            翻译后的语言
	 */
	public void setLanguage(Language from, Language to) {
		this.from = from.toString();
		this.to = to.toString();
	}
}
